/****************************************************************************
 * Copyright (C) 2012 Dj_Skual
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/
#include "ThemeThumbsTask.h"
#include "../../Controls/Application.h"
#include "../../Prompts/ProgressWindow.h"
#include "../../Network/http.h"
#include "../../FileOperations/fileops.h"

ThemeThumbsTask::ThemeThumbsTask(Theme_List * List, int firstitem)
	: list(List), firstItem(firstitem)
{
	running = true;
	
	for(int i = 0; i < 4; i++)
		thumbData[i] = NULL;
	
	ThreadedTaskHandler::Instance()->AddTask(this);
}

GuiImageData * ThemeThumbsTask::GetImageData(int index)
{
	GuiImageData * ImageData = NULL;
	char filepath[300];
	snprintf(filepath, sizeof(filepath), "%s/tmp/%s.jpg", Settings.ThemePath, list->GetThemeTitle(index));

	if (!CheckFile(filepath))
	{
		struct block file = downloadfile(list->GetImageLink(index));
		char storepath[300];
		snprintf(storepath, sizeof(storepath), "%s/tmp/", Settings.ThemePath);
		CreateSubfolder(storepath);
		if (file.data)
		{
			ImageData = new GuiImageData(file.data, file.size);
			
			FILE *storefile = fopen(filepath, "wb");
			if(storefile)
			{
				fwrite(file.data, 1, file.size, storefile);
				fclose(storefile);
			}
			free(file.data);
		}
	}
	else
		ImageData = new GuiImageData(filepath);

	return ImageData;
}

void ThemeThumbsTask::Execute(void)
{
	if(ProgressWindow::Instance()->IsRunning())
		ProgressWindow::Instance()->SetTitle(tr("Downloading image:"));
	else
		StartProgress(tr("Downloading image:"));

	int btnCount = 4;
	if(list->GetThemeCount()-firstItem < 4)
		btnCount = list->GetThemeCount()-firstItem;
	
	delayTimer.reset();
	
	int n = 0;
	for(int i = firstItem; i < (int) list->GetThemeCount() && i < firstItem+4; ++i)
	{
		ShowProgress(n, btnCount, list->GetThemeTitle(i));
		thumbData[n] = GetImageData(i);
		n++;
	}
	
	if(delayTimer.elapsedMilliSecs() > 500)
	{
		FinishProgress(btnCount);
		sleep(1);
	}
	
	StopProgress();
	while(ProgressWindow::Instance()->IsRunning())
		usleep(50);
	
	running = false;
}
